22. Flask + Pandas

Flask + Pandas

Flask and Pandas

Code from the Screencast

Here is the code from the routes.py file before refactoring.

The data set comes from this link at the World Bank's data repository: link to dataset

from worldbankapp import app
from flask import render_template
import pandas as pd

df = pd.read_csv('data/API_SP.RUR.TOTL.ZS_DS2_en_csv_v2_9948275.csv', skiprows=4)

# Filter for 1990 and 2015, top 10 economies
df = df[['Country Name','1990', '2015']]
countrylist = ['United States', 'China', 'Japan', 'Germany', 'United Kingdom', 'India', 'France', 'Brazil', 'Italy', 'Canada']
df = df[df['Country Name'].isin(countrylist)]

# melt year columns  and convert year to date time
df_melt = df.melt(id_vars='Country Name', value_vars = ['1990', '2015'])
df_melt.columns = ['country','year', 'variable']
df_melt['year'] = df_melt['year'].astype('datetime64[ns]').dt.year

# add column names
df_melt.columns = ['country', 'year', 'percentrural']

# prepare data into x, y lists for plotting
df_melt.sort_values('percentrural', ascending=False, inplace=True)

data = []
for country in countrylist:
    x_val = df_melt[df_melt['country'] == country].year.tolist()
    y_val =  df_melt[df_melt['country'] == country].percentrural.tolist()
    data.append((country, x_val, y_val))
    print(country, x_val, y_val)

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html')

@app.route('/project-one')
def project_one():
    return render_template('project_one.html')

Exercise

The next exercise will be after the section on using Plotly, Pandas, and Flask together. For now, the next part of the lesson has the refactored code shown in this screencast so that you can explore it in more detail. You'll find it in the 2_flask+pandas_example folder.